package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.Gjjutil.JiDaiApiUtil;
import com.block.datapush.service.apipush.utils.JinTongBaoUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 *  吉贷双授权
 */
@Service
public class JiDaiApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5());
        paramMap.put("nameMd5", SecureUtil.md5(memberSourceInfo.getRealname()));
        paramMap.put("sex", memberSourceInfo.getAge()==1?1:2);
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("xinyong", JiDaiApiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("occupation", JiDaiApiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("zhima", JiDaiApiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("gjj", JiDaiApiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("shebao", JiDaiApiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("car", JiDaiApiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", JiDaiApiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("baodan", JiDaiApiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("creditCard", JiDaiApiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("salaryType", "1");
        paramMap.put("monthIncome", JiDaiApiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("ip", memberSourceInfo.getReqIp());


        String encrypt = encrypt(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        String requestId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("reqId",requestId);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);


        log.info("【吉贷下游】撞库开始【queryUrl】{}【paramMap】{}【aceMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【吉贷下游】撞库结束【result】{}", result);
        log.info("【吉贷下游】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "0")) {
            JSONObject data = resultObject.getJSONObject("data");
            String logo = data.getString("logoUrl");
            String productName = data.getString("productName");
            String orgName = data.getString("productOrgName");
            String orderId = data.getString("orderId");
            // 撞库成功之后，商户的机构数据存储
            ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
            thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
            thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
            thirdInfoDTO.setOrderNo(requestId);
            JSONObject infoObject = new JSONObject();
            infoObject.put("productName",productName);
            infoObject.put("orderNo",requestId);
            infoObject.put("productId",requestId);
            infoObject.put("companyName",orgName);
            infoObject.put("companyLogo",logo);
            infoObject.put("maxLoanAmount","200000");
            infoObject.put("maxLoanRate","20");
            infoObject.put("minLoanRate","1");
            infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
            JSONArray jsonArray = new JSONArray();
            JSONArray protocolList = data.getJSONArray("protocolList");
            if (protocolList.size() != 0){
                for (Object o : protocolList) {
                    JSONObject jsonObject1 = new JSONObject();
                    String s = JSONObject.toJSONString(o);
                    JSONObject jsonObject = JSON.parseObject(s);
                    String protocolName = jsonObject.getString("protocolName");
                    String protocolUrl = jsonObject.getString("protocolUrl");
                    jsonObject1.put("protocalName",protocolName);
                    jsonObject1.put("protocalUrl",protocolUrl);
                    jsonArray.add(jsonObject1);
                }
            }
            infoObject.put("protocalList",jsonArray);
            thirdInfoDTO.setInfoObject(infoObject);

            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                String price = data.getString("price");//下游返回分润后价格
                BigDecimal priceNew = new BigDecimal(price);
                if (priceNew.compareTo(new BigDecimal(0.00)) == -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceLeft = priceNew.divide(typeRate);//分润前价格待定
                pushApiResult.setPrice(priceLeft);
                pushApiResult.setPriceRight(priceNew);
            }

            boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
            if (save){
                pushApiResult.setPushSuccess(true);
            }else{
                pushApiResult.setMessage("保存撞库数据失败");
            }

        }
        return pushApiResult;
    }



    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name", memberSourceInfo.getRealname());
        paramMap.put("sex", memberSourceInfo.getAge()==1?1:2);
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("xinyong", JiDaiApiUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("occupation", JiDaiApiUtil.getjob(memberSourceInfo.getGongzuo()));
        paramMap.put("zhima", JiDaiApiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("gjj", JiDaiApiUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("shebao", JiDaiApiUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("car", JiDaiApiUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", JiDaiApiUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("baodan", JiDaiApiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("creditCard", JiDaiApiUtil.getxinyongka(memberSourceInfo.getXinyongka()));
        paramMap.put("salaryType", "1");
        paramMap.put("monthIncome", JiDaiApiUtil.getShouRu(memberSourceInfo.getShouru()));
        paramMap.put("ip", memberSourceInfo.getReqIp());

        String encrypt = encrypt(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());

        Map<String, Object> aceMap = new HashMap<>();
        aceMap.put("reqId",orderNo);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);



        log.info("【吉贷下游】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);


        log.info("【吉贷下游】导单结束【result】{}", resultObject.toJSONString());


        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "|" + msg);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo);
        thirdInfoDTO.setRetCode(String.valueOf(code));
        thirdInfoDTO.setRetMsg(msg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (StrUtil.equals(String.valueOf(code), "200")){
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);
        if (StrUtil.equals(String.valueOf(code), "0" )) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }



    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
      return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static String encrypt(String contentStr, String key) {
        try {
            if(StringUtils.isEmpty(contentStr)) {
                return null;
            }
            byte[] raw = key.getBytes(StandardCharsets.UTF_8);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(contentStr.getBytes(StandardCharsets.UTF_8));
            return new Base64().encodeToString(encrypted);
        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
